import { defineStore } from 'pinia';
import axios from 'axios';
import router from '../router';

// 设置axios默认baseURL
axios.defaults.baseURL = 'http://localhost:3000/api';

// 请求拦截器，自动添加token
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 我们将在main.js中设置响应拦截器，避免循环引用问题

export const authStore = defineStore('auth', {
  state: () => ({
    user: null,
    token: null,
    isAuthenticated: false,
    loading: false,
    error: null
  }),

  actions: {
    // 登录
    async login(credentials) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.post('/users/login', credentials);
        this.user = response.data.user;
        this.token = response.data.token;
        this.isAuthenticated = true;
        
        // 保存到本地存储
        localStorage.setItem('token', this.token);
        localStorage.setItem('user', JSON.stringify(this.user));
        
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '登录失败，请检查用户名和密码';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 注册
    async register(userData) {
      this.loading = true;
      this.error = null;
      try {
        const response = await axios.post('/users/register', userData);
        return response.data;
      } catch (error) {
        this.error = error.response?.data?.message || '注册失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 获取当前用户信息
    async getCurrentUser() {
      try {
        const response = await axios.get('/users/me');
        this.user = response.data;
        this.isAuthenticated = true;
        return response.data;
      } catch (error) {
        this.logout();
        throw error;
      }
    },

    // 从本地存储加载用户信息
    loadFromStorage() {
      const token = localStorage.getItem('token');
      const user = localStorage.getItem('user');
      
      if (token && user) {
        this.token = token;
        this.user = JSON.parse(user);
        this.isAuthenticated = true;
        // 验证token是否有效
        this.getCurrentUser().catch(() => {
          this.logout();
        });
      }
    },

    // 登出
    logout() {
      this.user = null;
      this.token = null;
      this.isAuthenticated = false;
      localStorage.removeItem('token');
      localStorage.removeItem('user');
    }
  }
});